/**
 * CustomBindStatus.java
 *
 * Copyright 2010 Jack Leow
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package my.edu.clhs.springframework.web.servlet.view.stringtemplate3.support;

import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.support.RequestContext;

/**
 * Custom {@link BindStatus} implementation that adds a valueOptions property...
 *
 * TODO Document.
 *
 * @author Jack Leow
 * @version 1.0
 * @since 1.0 (Dec 14, 2010, 2:03:00 PM)
 */
class CustomBindStatus extends BindStatus {
    // TODO logging
    public CustomBindStatus(RequestContext requestContext, String path) {
        super(requestContext, path, false);
    }
    
    public Map getValueOptions() {
        return new AbstractMap() {
            // @Override
            public Set entrySet() {
                throw new UnsupportedOperationException("not implemented");
            }
            
            // @Override
            public boolean containsKey(Object key) {
                return key instanceof Collection || key instanceof Object[] ||
                    key instanceof boolean[] || key instanceof char[] ||
                    key instanceof byte[] || key instanceof short[] ||
                    key instanceof int[] || key instanceof long[] ||
                    key instanceof float[] || key instanceof double[];
            }
            
            private List toBoxedList(Object primitiveArray) {
                List boxed;
                
                if (primitiveArray instanceof boolean[]) {
                    boolean[] primitive = (boolean[])primitiveArray;
                    boxed = new ArrayList(primitive.length);
                    for (int i = 0; i < primitive.length; ++ i) {
                        boxed.add(Boolean.valueOf(primitive[i]));
                    }
                } else if (primitiveArray instanceof char[]) {
                    char[] primitive = (char[])primitiveArray;
                    boxed = new ArrayList(primitive.length);
                    for (int i = 0; i < primitive.length; ++ i) {
                        boxed.add(new Character(primitive[i]));
                    }
                } else if (primitiveArray instanceof byte[]) {
                    byte[] primitive = (byte[])primitiveArray;
                    boxed = new ArrayList(primitive.length);
                    for (int i = 0; i < primitive.length; ++ i) {
                        boxed.add(new Byte(primitive[i]));
                    }
                } else if (primitiveArray instanceof short[]) {
                    short[] primitive = (short[])primitiveArray;
                    boxed = new ArrayList(primitive.length);
                    for (int i = 0; i < primitive.length; ++ i) {
                        boxed.add(new Short(primitive[i]));
                    }
                } else if (primitiveArray instanceof int[]) {
                    int[] primitive = (int[])primitiveArray;
                    boxed = new ArrayList(primitive.length);
                    for (int i = 0; i < primitive.length; ++ i) {
                        boxed.add(new Integer(primitive[i]));
                    }
                } else if (primitiveArray instanceof long[]) {
                    long[] primitive = (long[])primitiveArray;
                    boxed = new ArrayList(primitive.length);
                    for (int i = 0; i < primitive.length; ++ i) {
                        boxed.add(new Long(primitive[i]));
                    }
                } else if (primitiveArray instanceof float[]) {
                    float[] primitive = (float[])primitiveArray;
                    boxed = new ArrayList(primitive.length);
                    for (int i = 0; i < primitive.length; ++ i) {
                        boxed.add(new Float(primitive[i]));
                    }
                } else if (primitiveArray instanceof double[]) {
                    double[] primitive = (double[])primitiveArray;
                    boxed = new ArrayList(primitive.length);
                    for (int i = 0; i < primitive.length; ++ i) {
                        boxed.add(new Double(primitive[i]));
                    }
                } else {
                    throw new IllegalArgumentException(
                        "primitiveArray must be a primitive array");
                }
                
                return boxed;
            }
            
            private Collection toSelectableOptions(final Collection input) {
                Object rawValue = getActualValue();
                if (rawValue instanceof Object[]) {
                    rawValue = Arrays.asList(
                        (Object[])rawValue);
                } else if (rawValue instanceof boolean[] ||
                        rawValue instanceof char[] ||
                        rawValue instanceof byte[] ||
                        rawValue instanceof short[] ||
                        rawValue instanceof int[] ||
                        rawValue instanceof long[] ||
                        rawValue instanceof float[] ||
                        rawValue instanceof double[]) {
                    rawValue = toBoxedList(rawValue);
                }
                final Object selectedValue = rawValue;
                
                return new AbstractCollection() {
                    // @Override
                    public int size() {
                        return input.size();
                    }
                    
                    // @Override
                    public Iterator iterator() {
                        return new Iterator() {
                            private Iterator wrapped = input.iterator();
                            
                            // @Override
                            public void remove() {
                                throw new UnsupportedOperationException(
                                    "immutable iterator");
                            }
                            
                            // @Override
                            public Object next() {
                                Object value = wrapped.next();
                                
                                return new SelectableOption(
                                    value,
                                    selectedValue instanceof Collection ?
                                        ((Collection)selectedValue).
                                            contains(value) :
                                        value == null ?
                                            selectedValue == null :
                                            value.equals(selectedValue)
                                );
                            }
                            
                            // @Override
                            public boolean hasNext() {
                                return wrapped.hasNext();
                            }
                        };
                    }
                };
            }
            
            // TODO consider returning collection instead of array on array inputs
            // @Override
            public Object get(Object key) {
                Object value = null;
                
                if (key instanceof Collection) {
                    value = toSelectableOptions((Collection)key);
                } else if (key instanceof Object[]) {
                    Collection selectableOptions =
                        toSelectableOptions(Arrays.asList((Object[])key));
                    value = new ArrayList(selectableOptions).toArray(
                        new SelectableOption[selectableOptions.size()]);
                } else if (key instanceof boolean[] || key instanceof char[] ||
                        key instanceof byte[] || key instanceof short[] ||
                        key instanceof int[] || key instanceof long[] ||
                        key instanceof float[] || key instanceof double[]) {
                    Collection selectableOptions =
                        toSelectableOptions(toBoxedList(key));
                    value = new ArrayList(selectableOptions).toArray(
                        new SelectableOption[selectableOptions.size()]);
                }
                
                return value;
            }
        };
    }
}